﻿using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Workbench.Operations;

namespace Workbench.Presentation
{
    /// <summary>
    /// Interaction logic for WordListView.xaml
    /// </summary>
    public partial class WordListView : UserControl
    {
        private WordListViewModel viewModel;
        public WordListViewModel ViewModel
        {
            get { return viewModel; }
            set
            {
                if (viewModel != null)
                {
                    viewModel.Error -= viewModel_Error;
                }
                viewModel = value;
                viewModel.Error += viewModel_Error;
            }
        }

        void viewModel_Error(string message)
        {
            MessageBox.Show(this.GetWindow(), message, "Error");
        }

        public WordListView()
        {
            InitializeComponent();
        }

        private void ExportCSVCommand_Click(object sender, RoutedEventArgs e)
        {
            if (!ProjectOperations.HasOpenedProject && viewModel != null)
                return;

            var dlg = new Microsoft.Win32.SaveFileDialog()
            {
                DefaultExt = ".csv",
                Filter = "Comma separated value Files (*.csv)|*.csv",
                ValidateNames = true,
                InitialDirectory = ProjectOperations.GetOpenedProjectFilePath(),
                CheckPathExists = true,
                OverwritePrompt = true,
                AddExtension = true,
            };

            Nullable<bool> result = dlg.ShowDialog();
            if (result == true)
            {
                viewModel.ExportCSVCommand.Execute(dlg.FileName);
            }
        }

        private void UserControl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            ViewModel = e.NewValue as WordListViewModel;
        }
    }
}
